package cn.datawin.crule;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.datawin.Rule;
import cn.datawin.Service;

public abstract class CoRule implements Rule{
	
	private Service service;
	
	Logger log = LoggerFactory.getLogger(getClass());
	
	private Map<String, Method> methods = new HashMap<String, Method>();
	
	private Map<String, Object> params = new HashMap<String, Object>();

	 private void setMethod(Method me, String name){
		synchronized (methods) {
			methods.put(name, me);
		}
	};
	
	private Method findMethod(String name){
		try {
			Method me = this.getClass().getDeclaredMethod(name);
			if(me!= null){
				setMethod(me, name);
				return me;
			}
			return null;
		} catch (Exception e) {
			log.error("findMethod", e);
			return null;
		} 
	}
	
	@Override
	public void next(String ruleName) {
		try {
			Method me  =  methods.get(ruleName);
			if(me == null) me = findMethod(ruleName);
			me.invoke(this);
			Service cs = getService();
			cs.exec();
		} catch (Exception e) {
			log.error("next", e);
		}
	}
	
	@Override
	public void do_(String ruleName) {
		next(ruleName);
	}
	
	@Override
	public <T> void setObject(T t) {
		params.put(t.getClass().getName() , t);
	};
	
	@Override
	public <T> T getObject(Class<T> _class) {
		return (T) params.get(_class.getName());
	}

	@Override
	public Service getService() {
		return this.service;
	}

	@Override
	public void setService(Service service) {
		this.service = service;
	}
	
}
